package com.xxl.job.executor.service.jobhandler;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHander;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.executor.service.util.AuthUtilService;
import com.xxl.job.executor.service.util.HttpUtilService;

@JobHander(value="CurlJobHandler")
@Service
public class CurlJobHandler extends IJobHandler {
	
	@Override
	public ReturnT<String> execute(String... params) throws Exception {		
		Map paramMap = parseParam(params);
		String url = paramMap.get("url").toString();
		String key = "testKey";
		String result = this.sendPost(url, paramMap, key);
		XxlJobLogger.log("result:" + result);
		/**
		HttpUtilService util = new HttpUtilService();  
		util.queryUrl(url, paramMap);		
		**/
		return new ReturnT(ReturnT.SUCCESS_CODE,"执行失败");
	}
	
	
	
	/**
	 * 发送get请求，发送到指定地址
	 * @param url 请求的地址
	 * @param params 请求参数
	 * @param key 生成hash的key
	 * 
	 * @return String 执行结果
	 */
	public  String sendPost(String url, Map<String, Object> params, String key) {
		PrintWriter out;
        BufferedReader in;
        String result = "";
        String auth = AuthUtilService.createAuth(key, params);
        try {     	
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("auth", auth);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            JSONObject jsonObject = new JSONObject(params);
            out.print(jsonObject.toString());
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+ e.getMessage());
            e.printStackTrace();
        }
        return result;
    } 
	
	/**
	 * 解析调度器分发的参数，并从数据中获取任务相关的数据
	 * 
	 * 
	 */
	public Map<String, Object>parseParam(String[] params)
	{
		Map param = new HashMap<String, Object>();
		for(int i=0;i<params.length;i++)
		{
			String[] strarr = params[i].split("=");
			param.put(strarr[0], strarr[1]);
		}
		return param;
	}
	
}
